package com.punai.config.sqlitedao.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.sqlite.SqliteUtil;
import com.punai.config.constants.PnConfigConstants;
import com.punai.config.sqlitedao.StructureRepository;
import com.punai.config.sqlitedomain.Structure;
import com.punai.config.sqlitesetting.SqliteSystemTemplConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class StructureRepositoryImpl implements StructureRepository {
    private static SqliteUtil sqliteUtil;
    private static final Logger log = LoggerFactory.getLogger(TemplateRepositoryImpl.class);

    @Autowired
    private SqliteSystemTemplConnection sqliteSystemTemplConnection;

    private void initConnection() {
        sqliteUtil = sqliteSystemTemplConnection.initConnection();
    }

    @Override
    public Structure findOne(String id)  {
        if (StrUtil.isBlank(id)) throw new ServiceException("指标表查找失败：id不能为空");
        initConnection();
        String sql = "select * from tab_config_indicator_struts where id = '" + id + "'";
        Structure structure = sqliteUtil.selectOneRecord(Structure.class, sql);
        return structure;
    }

    @Override
    public List<Structure> findByTemplateId(String templateId)  {
        if (StrUtil.isBlank(templateId)) throw new ServiceException("指标表查找失败：模板id不能为空");
        initConnection();
        String sql = "select " +
                "* " +
                "from " +
                "tab_config_indicator_struts struts " +
                "left join " +
                "tab_config_link_strut_template link " +
                "on link.struts_id = struts.id " +
                "where link.template_id = '"+ templateId+"' " +
                "order by struts.sorting";
        return sqliteUtil.selectListRecord(Structure.class, sql);
    }

    @Override
    public Integer findMaxSorting() {
        initConnection();
        String sql = "select max(sorting) as sorting from tab_config_indicator_struts";
        Structure structure = sqliteUtil.selectOneRecord(Structure.class, sql);
        return structure.getSorting();
    }

    @Override
    public Structure save(Structure structure)  {
        initConnection();
        if(StrUtil.isNotBlank(structure.getId())){
            return this.update(structure);
        }else{
            String Sql = "insert into "
                    + "tab_config_indicator_struts(ID,NAME,CODE,PARENT_ID,UNIT,IS_GROUP_DATA,"
                    + "DATA_TYPE,SORTING,CREATE_DATE,LAST_MODIFY,EDIT_STATE,SREACH_KEY,VERSION,TYPE,SPECIALITY,SHOW_RULE,calculation_code) "
                    + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
            structure.setSorting(this.findMaxSorting() + 1);
            structure.setEditState(PnConfigConstants.EDITSTATE.SAVESTATE.getType());
            structure.setVersion(Integer.parseInt(String.valueOf(PnConfigConstants.ENTITY_VERSION)));
            structure.setSreachKey(structure.toString());
            structure.setId(IdUtil.fastUUID());
            Object[] args = new Object[]{
                    structure.getId(),
                    structure.getName(),
                    structure.getCode(),
                    structure.getParentId(),
                    structure.getUnit(),
                    structure.getIsGroupData(),
                    structure.getDataType(),
                    structure.getSorting(),
                    new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                    new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                    structure.getEditState(),
                    structure.getSreachKey(),
                    structure.getVersion(),
                    structure.getType(),
                    structure.getSpeciality(),
                    structure.getShowRule(),
                    structure.getCalculationCode()
            };
            int rownumber = sqliteUtil.execute(Sql, args);
            if (rownumber == 0) {
                throw new ServiceException("sqlite.message.addException");
            }
        }
        return structure;
    }

    @Override
    public Structure update(Structure structure)  {
        initConnection();
        String Sql = "update tab_config_indicator_struts set "+
                "NAME=?," +
                "CODE=?," +
                "PARENT_ID=?," +
                "UNIT=?," +
                "IS_GROUP_DATA=?,"+
                "DATA_TYPE=?," +
                "SORTING=?," +
                "LAST_MODIFY=?," +
                "EDIT_STATE=?," +
                "SREACH_KEY=?," +
                "TYPE=?," +
                "SPECIALITY=?," +
                "SHOW_RULE=?," +
                "calculation_code=? "+
                "where id = ?";
        structure.setSreachKey(structure.toString());
        Object[] args = new Object[]{
                structure.getName(),
                structure.getCode(),
                structure.getParentId(),
                structure.getUnit(),
                structure.getIsGroupData(),
                structure.getDataType(),
                structure.getSorting(),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                PnConfigConstants.EDITSTATE.UPDATESTATE.getType(),
                structure.getSreachKey(),
                structure.getType(),
                structure.getSpeciality(),
                structure.getShowRule(),
                structure.getCalculationCode(),
                structure.getId()
        };
        int rownumber = sqliteUtil.execute(Sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.updateException");
        }
        return  structure;
    }

    @Override
    public void remove(String strutsId)  {
        if(StrUtil.isBlank(strutsId)) throw new ServiceException("删除指标失败：指标表Id不能为空");
        initConnection();
        String Sql = "delete from tab_config_indicator_struts where id = '"+strutsId+"'";
        int rownumber = sqliteUtil.execute(Sql);
    }

    @Override
    public List<Structure> findByParentId(String parentId) {
        initConnection();
        String sql = "select " +
                "* " +
                "from " +
                "tab_config_indicator_struts " +
                "where " +
                "PARENT_ID = '" + parentId + "' ";
        return sqliteUtil.selectListRecord(Structure.class, sql);
    }

    @Override
    public void updateSort(String id, int i) {
        initConnection();
        String sql = "update tab_config_indicator_struts set SORTING = " + i + " where id = '" + id + "'";
        int execute = sqliteUtil.execute(sql);
    }
}